<template>
    <div>
        <el-card>
            <el-form :model="queryForm" :inline='true'>
                <el-form-item label="官方号选择">
                    <el-select v-model="queryForm.userId" size="small">
                        <el-option v-for="(item,index) in idList" :key="'userId-'+index" :value="item.id" :label="item.nickname"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="size" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="size" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="mt12">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" @click="handleBatchDelete()">删除</el-button>
                </div>
                <div class="right-btns">
                    <el-button size="small" icon="el-icon-refresh" circle @click="getList"></el-button>
                </div>
            </div>
            <el-table :data="userList" style="wdith:100%" border class="mt12">
                <el-table-column type="selection" width="50px"></el-table-column>
                <el-table-column prop="id" label="ID" width="60px"></el-table-column>
                <el-table-column prop="title" label="标 题"></el-table-column>
                <el-table-column prop="nickname" label="用户昵称"></el-table-column>
                <el-table-column prop="content" label="内 容">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top" width="300">
                            <p>{{scope.row.content}}</p>
                            <div slot="reference">
                            <span class="ellipsis">{{scope.row.content}}</span>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="watchCount" sortable label="观看数量" width="120px"></el-table-column>
                <el-table-column prop="remarkCount" sortable label="评论数量" width="120px"></el-table-column>
                <el-table-column prop="likeCount" sortable label="获赞数量" width="120px"></el-table-column>
                <el-table-column prop="createTime" sortable label="发布时间"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-link icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-link>
                        <el-link icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
            :current-page="queryForm.pageNo" 
            :page-size="queryForm.pageSize"
            :total="total"
            :page-sizes="[10,20,50,100]"
            layout="total,sizes,prev,pager,next"
            @current-change='handleCurrentChange'
            @size-change='handleSizeChange'>
            </el-pagination>
        </el-card>
        <el-dialog :title="title" :visible.sync="show" >
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules='rules' ref="submitForm">
                <el-row>
                    <el-col>
                        <el-form-item label="官方号选择"  prop="userId">
                            <el-select v-model="submitForm.userId" size="small" @change="changeSelect">
                                <el-option v-for="(item,index) in idList" :key="'userId-'+index" :value="item.id" :label="item.nickname"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="帖子标题" prop="title">
                            <el-input type="text" v-model="submitForm.title"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="帖子内容"  prop="content" >
                            <el-input type="textarea" :rows="8" v-model="submitForm.content" style="width:600px;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="uploadShow">
                    <el-col>
                        <el-form-item label="帖子图片">
                            <el-upload
                            class="upload-demo"
                            action="/app-api/app/post/upload"
                            :headers="headers"
                            :data="data"
                            :file-list="fileList"
                            :limit="9"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button></el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            
            <div class="dialog-footer" slot="footer">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {listPost,getPost,delPost,updatePost,addPost,getPostCount} from '@/api/Post'
    export default {
        name:'AdminPost',
        data(){
            return{
                total:120,
                queryForm:{
                    pageNum:1,
                    pageSize:10,
                    orderByColumn:'id',
                    isAsc:'desc'
                },
                show:false,
                title:"新增",
                selectList:[],
                submitForm:[],
                //官方号
                idList:[
                    {id:4,nickname:"森辉岛泰拉信使公署"},
                    {id:5,nickname:"明日方舟"}
                ],
                userList:[],
                headers:{
                    Authorization:"Bearer"+localStorage.getItem("login-token")
                },
                data:{
                    userId:0,
                    postCount:0
                },
                fileList:[],
                uploadShow:true,
                rules:{
                    title:[
                        {required:true,message:'请输入标题',trigger:'blur'},
                        {min:6,max:16,message:'长度必须在16之间',trigger:'blur'}
                    ],
                    userId:[
                        {required:true,message:'请选择官方号',trigger:'blur'}
                    ]
                }
            }
        },
        created(){
            this.getList()
        },
        methods:{
            handleSubmit(){
                console.log(this.submitForm)
                this.$refs['submitForm'].validate((valid)=>{
                    console.log("valid---",valid)
                    if(valid){
                        if(this.submitForm.id){
                            updatePost(this.submitForm).then(res=>{
                                this.show = false
                                this.submitForm = {}
                                this.getList()
                            }).catch(err=>{
                                console.log(err)
                            })
                        }else{
                            this.submitForm.image = '{"userId":' + this.data.userId + ',"postCount":' + this.data.postCount + ',"imgCount": 1}'
                            this.submitForm.status = 1
                            addPost(this.submitForm).then(res=>{
                                this.show = false
                                this.submitForm = {}
                                this.getList()
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                        
                    }
                })
            },
            handleReset(){
                this.queryForm = {
                    pageNum:1,
                    pageSize:10
                }
                this.getList()
            },
            handleSearch(){
                this.queryForm.pageNum = 1
                this.getList()
            },
            handleSizeChange(pageSize){
                this.queryForm.pageSize = pageSize
                this.queryForm.pageNum = 1
                this.getList()
            },
            handleCurrentChange(pageNum){
                this.queryForm.pageNum = pageNum
                this.getList()
            },
            getList(){
                this.userList = []
                if(this.queryForm.userId == null){
                    for(var i=0;i < this.idList.length;i++){
                        var temp = {
                                pageNum:1,
                                pageSize:10,
                                userId:this.idList[i].id
                            }
                        listPost(temp).then(res=>{
                            for(var j=0;j < res.data.records.length;j++){
                                this.userList.push(res.data.records[j])
                                this.userList[j].createTime = this.formatDate(this.userList[j].createTime)
                            }
                            this.total = res.data.total
                        }).catch(err=>{console.log(err)})             
                    }

                }else{
                    listPost(this.queryForm).then(res=>{
                        this.userList = res.data.records
                        for(var i=0;i < this.userList.length;i++){
                            this.userList[i].createTime = this.formatDate(this.userList[i].createTime)
                        }
                        this.total = res.data.total
                    }).catch(err=>{console.log(err)})
                }
            },
            handleDelete(id){
                this.$confirm("你确定删除id为"+id+"的记录吗？","提示",{
                    cancelButtonText:"取消",
                    confirmButtonText:"确定",
                    type:"warning"
                }).then(()=>{
                    //调接口删除
                    delPost(id).then(res => {
                        //提示删除成功
                        this.$message("删除成功")
                        //刷新列表
                        this.getList()
                    }).catch(err=>{
                        console.log(err)
                    })
                }).catch(()=>{})
            },
            handleAdd(){
                this.show = true
                this.uploadShow = true
                this.title = "新增"
                this.submitForm = {}
            },
            handleCancel(){
                this.show = false
            },
            handleEdit(id){
                this.uploadShow = false
                getPost(id).then(res=>{
                    //调接口获取最新数据
                    this.show = true
                    this.title = "编辑"
                    this.submitForm = res.data
                }).catch(err=>{
                    console.log(err)
                })
            },
            handleBatchDelete(){
                console.log(this.selectList)
                if(this.selectList){
                    let ids = this.selectList.map(o => {return o.id})
                    console.log('ids---------->',ids)
                    this.handleDelete(ids)
                }
            },
            handleSelectionChange(val){//当我们选择时会回调这个函数
                this.selectList = val;
                console.log(val)
            },
            changeSelect(value){
                this.data.userId = value
                getPostCount(value).then(res=>{
                    this.data.postCount = res.data+1
                })
            },
            formatDate(value) {
                const date = new Date(value);
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                const day = date.getDate();
                const hours = date.getHours();
                const minutes = date.getMinutes();
                const seconds = date.getSeconds();
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
        }
    }
</script>

<style  scoped>
    .el-form-item{
        margin: 10px 30px;
    }
    .handel-btns{
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .el-link{
        margin: 0 5px;
        font-size: 12px;
    }
    .ellipsis {
        display:-webkit-box;
        text-overflow:ellipsis;
        overflow:hidden;
        -webkit-line-clamp: 2;
        -webkit-box-orient:vertical;
    }
    .el-popover{
        height: 150px;
        overflow: auto;
    }
</style>